package com.wnxy.sddfp.system;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

public class App {
    @Test
    public void createToken() {
        // 构造token数据
        Map<String,Object> payload = new HashMap<>();
        payload.put("id",100);

        // 创建工厂
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource("jwt.jks"),"123456".toCharArray());

        // 创建密钥对对象
        KeyPair keyPair = factory.getKeyPair("jwt");

        // 创建签名器对象
        JWTSigner jwtSigner = JWTSignerUtil.createSigner("RSA",keyPair);

        // 生成token
        String token = JWTUtil.createToken(payload, jwtSigner);
        System.out.println("token = " + token);

        // 验签
        boolean verify = JWTUtil.verify(token, jwtSigner);
        if (verify) {
            // 获取token数据
            JWT jwt = JWTUtil.parseToken(token);
            Object id = jwt.getPayload("id");
            System.out.println("id = " + id);
        }
    }
}
